<template>
    <n-form :model="form" :rules="rules" ref="formRef" size="large">
        <n-form-item  path="username">
            <n-input placeholder="请输入用户名" v-model:value="form.username"/>
        </n-form-item>
        <n-form-item path="password">
            <n-input type="password" placeholder="请输入密码" v-model:value="form.password"/>
        </n-form-item>
        <n-form-item path="againPassword">
            <n-input type="password" :disabled="!form.password" placeholder="请输入密码"
                     v-model:value="form.againPassword" @keydown.enter.prevent="handleRegister"/>
        </n-form-item>
    </n-form>
    <n-button type="success"
              size="large"
              circle
              :loading="loading"
              class="bg-green-600 dark:bg-green-400"
              block @click="handleRegister">
        注册
    </n-button>
</template>

<script setup lang="ts">
import {ref} from "vue";
import {FormItemRule} from "naive-ui";
import api from "@/api";
import {debounce, encrypt} from "@/utils";



const loading =ref(false)
const form = ref({
    username: '',
    password: '',
    againPassword: '',
})
const formRef = ref()
const rules = ref({
    username: [{
        required: true,
        message: '请输入用户名',
        trigger: ['input']
    }],
    password: [{
        required: true,
        message: '请输入密码',
        trigger: ['input']
    }, {
        validator: validatePasswordStartWith,
        message: '两次密码输入不一致',
        trigger: 'input'
    }],
    againPassword: [{
        required: true,
        message: '请再次输入密码',
        trigger: ['input']
    }, {
        validator: validatePasswordSame,
        message: '两次密码输入不一致',
        trigger: 'input'
    }]
})



const handleRegister = debounce(() => {
    formRef.value.validate((error: any) => {
        if (!error) {
            loading.value=true
            api.user.register({
                username: form.value.username,
                password: encrypt(form.value.password)
            }).then((res: any) => {
              if (res.data.code === 0) {
                window.$message.success('注册成功')
              }
            }).finally(()=>{
                loading.value=false
            })
        }
    })
}, 200)

function validatePasswordStartWith(
    rule: FormItemRule,
    value: string
): boolean {
    console.log(rule)
    return (
        !!form.value.password &&
        form.value.password.startsWith(value) &&
        form.value.password.length >= value.length
    )
}

function validatePasswordSame(rule: FormItemRule, value: string): boolean {
    console.log(rule)
    return value === form.value.password
}

</script>

<style scoped>

</style>
